package b2.widget
{
	import b2.scene.*;
	import b2.util.*;
	
	import flash.display.*;
	import flash.events.*;
	
	public class WidgetManager
	{
		static private var instance:WidgetManager;
		public var mouseOverMessage:Sprite;
		
		public function WidgetManager()
		{
		}

		static public function getInstance():WidgetManager
		{
			if (!instance)
				instance = new WidgetManager();
			return instance;
		}
		
		//打开鼠标悬浮窗口
		public function popOutMouseOverMessage(widget:Sprite):void
		{
			closeMouseOverMessage();
			mouseOverMessage = widget;
			SceneManager.getInstance().currentScene.addChild(widget);
		}
		
		//关闭鼠标悬浮窗口
		public function closeMouseOverMessage():void
		{
			if (mouseOverMessage != null && mouseOverMessage.parent != null)
				mouseOverMessage.parent.removeChild(mouseOverMessage);
			mouseOverMessage = null;
		}
		
		public function getWidget(DialogClass:Class):DisplayObject
		{
			var scene:BasicScene = SceneManager.getInstance().currentScene;
			for (var i:int = 0; i < scene.numChildren; i++)
			{
				var widget:DisplayObject = scene.getChildAt(i);
				if (widget is DialogClass)
					return widget;
			}
			return null;
		}
		
		public function popOut(widgets:Array, exclusive:Boolean = false, center:Boolean = false):void
		{
			for (var i:int = 0; i < widgets.length; i++)
			{
				var widget:Sprite = widgets[i];
				if (center)
				{
					widget.x = (BFont.stageWidth - widget.width) / 2;
					widget.y = (BFont.stageHeight - widget.height) / 2;
				}
				if (exclusive && i == 0)
				{
					addTransparentBgr(widget);
				}
				SceneManager.getInstance().currentScene.addChild(widget);
			}
			BSound.getInstance().playEffect("SoundButton1");
		}
		
		private function addTransparentBgr(widget:Sprite):void
		{
			widget.addEventListener(Event.REMOVED_FROM_STAGE, onExclusiveWidgetRemoved);
			widget.addEventListener(Event.ADDED_TO_STAGE, onExclusiveWidgetAdded);
		}
		
		private function onExclusiveWidgetRemoved(event:Event):void
		{
			var widget:Sprite = event.currentTarget as Sprite;
			widget.parent.removeChildAt(widget.parent.getChildIndex(widget) - 1);
		}

		private function onExclusiveWidgetAdded(event:Event):void
		{
			var widget:Sprite = event.currentTarget as Sprite;
			var transparentBgr:Sprite = new Sprite();
			var gfx:Graphics = transparentBgr.graphics;
			gfx.clear();
			gfx.moveTo(0, 0);
			gfx.beginFill(0x000000, 0.3);
			gfx.lineTo(BFont.stageWidth, 0);
			gfx.lineTo(BFont.stageWidth, BFont.stageHeight);
			gfx.lineTo(0, BFont.stageHeight);
			gfx.lineTo(0, 0);
			gfx.endFill();
			widget.parent.addChildAt(transparentBgr, widget.parent.getChildIndex(widget));
		}
	}
}